<?php
namespace app\source\controller;

use app\common\controller\Api;

/**
 * 会员接口
 */
class Business extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
        
    public function __construct()
    {
        parent::__construct();

        $this->BusinessModel = model('Business');
        $this->RegionModel = model('Region');
    }

    /**
     * 会员注册
     *
     * @ApiTitle    (会员注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (/source/business/register)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号码")
     * @ApiParams   (name="password", type="string", required=true, description="密码")
     * @ApiReturnParams   (name="code", type="integer", sample="0", description="状态码")
     * @ApiReturnParams   (name="msg", type="string", sample="返回成功", description="返回信息")
     * @ApiReturnParams   (name="data", type="object", sample="null", description="返回数据")
     * @ApiReturn   ({
            "code": 1,
            "msg": "注册成功",
            "time": "时间戳",
            "data": null
        })
     */
    public function register()
    {
        if ($this->request->isPost()) 
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            // 密码盐
            $salt = randstr();

            // 密码加密
            $password = md5($password . $salt);

            $data = [
                'nickname' => $mobile,
                'mobile' => $mobile,
                'password' => $password,
                'salt' => $salt
            ];

            $result = $this->BusinessModel->validate('common/Business')->save($data);

            if ($result) 
            {
                $this->success('注册成功');
            } else 
            {
                $this->error($this->BusinessModel->getError());
            }
        }
    }

    /**
     * 会员登录
     *
     * @ApiTitle    (会员登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/source/business/login)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号码")
     * @ApiParams   (name="password", type="string", required=true, description="密码")
     * @ApiReturnParams   (name="code", type="integer", sample="0", description="状态码")
     * @ApiReturnParams   (name="msg", type="string", sample="返回成功", description="返回信息")
     * @ApiReturnParams   (name="data", type="object", sample="null", description="返回数据")
     * @ApiReturn   ({
            "code": 1,
            "msg": "登陆成功",
            "time": "1683970840",
            "data": {
                "id": 5,
                "mobile": "13512611223", //手机号码
                "nickname": "RickyFlex", //昵称
                "avatar": "http://www.api.com/uploads/20230511/6501ee41d32001f31f86fc053337eea6.jpg", //头像
                "gender": "2", //性别
                "province": "广东省", //省份
                "city": "广州市", //城市
                "district": "海珠区", //地区
                "region": "广东省-广州市-海珠区", //集合
                "createtime": 1683363865, //注册时间
                "address": "123123", //详细地址
            }
        })
     */
    public function login()
    {
        if ($this->request->isPost()) 
        {
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            // 查找当前手机号码
            $business = $this->BusinessModel->where(['mobile'=>$mobile])->find();

            if (!$business) 
            {
                $this->error('用户不存在');
                exit;
            }

            $password = md5($password . $business['salt']);

            if ($password != $business['password']) 
            {
                $this->error('密码错误');
                exit;
            }

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'nickname' => $business['nickname'],
                'avatar' => $business['avatar_text'],
                'gender' => $business['gender'],
                'province' => $business['province_text'],
                'city' => $business['city_text'],
                'district' => $business['district_text'],
                'region' => $business['region_text'],
                'createtime' => $business['createtime'],
                'address' => $business['address'],
            ];

            $this->success('登陆成功', $data);
        }
    }

    /**
     * 检查是否登录
     *
     * @ApiTitle    (检查是否登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/source/business/check)
     * @ApiParams   (name="id", type="string", required=true, description="ID")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号码")
     * @ApiReturnParams   (name="code", type="integer", sample="0", description="状态码")
     * @ApiReturnParams   (name="msg", type="string", sample="返回成功", description="返回信息")
     * @ApiReturnParams   (name="data", type="object", sample="null", description="返回数据")
     * @ApiReturn   ({
            "code": 1,
            "msg": "检查登录成功",
            "time": "时间戳",
            "data": {
                "id": 5,
                "mobile": "13512611223", //手机号码
                "nickname": "RickyFlex", //昵称
                "avatar": "http://www.api.com/uploads/20230511/6501ee41d32001f31f86fc053337eea6.jpg", //头像
                "gender": "2", //性别
                "province": "广东省", //省份
                "city": "广州市", //城市
                "district": "海珠区", //地区
                "region": "广东省-广州市-海珠区", //集合
                "createtime": 1683363865, //注册时间
                "address": "123123", //详细地址
            }
        })
     */
    public function check()
    {
        if ($this->request->isPost()) 
        {            
            $id = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            //根据ID和手机号码条件查找用户
            $where = [
                'id'=>$id,
                'mobile' => $mobile
            ];

            $business = $this->BusinessModel->where($where)->find();
            
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'nickname' => $business['nickname'],
                'avatar' => $business['avatar_text'],
                'gender' => $business['gender'],
                'province' => $business['province_text'],
                'city' => $business['city_text'],
                'district' => $business['district_text'],
                'region' => $business['region_text'],
                'createtime' => $business['createtime'],
                'address' => $business['address'],
            ];

            $this->success('检查登陆成功', $data);
        }
    }

    /**
     * 修改会员资料
     *
     * @ApiTitle    (修改会员资料)
     * @ApiMethod   (POST)
     * @ApiRoute    (/source/business/profile)
     * @ApiParams   (name="id", type="string", required=true, description="ID")
     * @ApiParams   (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号码")
     * @ApiParams   (name="password", type="string", required=false, description="密码")
     * @ApiParams   (name="gender", type="string", required=true, description="性别")
     * @ApiParams   (name="avatar", type="file", required=false, description="头像")
     * @ApiParams   (name="region", type="string", required=false, description="地区码")
     * @ApiParams   (name="address", type="string", required=false, description="详细地址")
     * @ApiReturnParams   (name="code", type="integer", sample="0", description="状态码")
     * @ApiReturnParams   (name="msg", type="string", sample="返回成功", description="返回信息")
     * @ApiReturnParams   (name="data", type="object", sample="null", description="返回数据")
     * @ApiReturn   ({
            "code": 1,
            "msg": "修改个人资料成功",
            "time": "时间戳",
            "data": {
                "id": 5,
                "mobile": "13512611223", //手机号码
                "nickname": "RickyFlex", //昵称
                "avatar": "http://www.api.com/uploads/20230511/6501ee41d32001f31f86fc053337eea6.jpg", //头像
                "gender": "2", //性别
                "province": "广东省", //省份
                "city": "广州市", //城市
                "district": "海珠区", //地区
                "region": "广东省-广州市-海珠区", //集合
                "createtime": 1683363865, //注册时间
                "address": "123123", //详细地址
            }
        })
     */
    public function profile()
    {
        if ($this->request->isPost()) 
        {            
            $id = $this->request->param('id', 0, 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            
            // 根据ID查找用户是否存在
            $business = $this->BusinessModel->find($id);
            
            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }

            //组装数据
            $data = [
                'id' => $id,
                'mobile' => $mobile,
                'nickname' => $this->request->param('nickname', '', 'trim'),
                'gender' => $this->request->param('gender', 0, 'trim'),
                'address' => $this->request->param('address', '', 'trim')
            ];

            //判断是否有密码修改
            $password = $this->request->param('password', '', 'trim');

            if(!empty($password))
            {
                // 密码盐
                $salt = randstr();

                // 密码加密
                $password = md5($password . $salt);

                $data['salt'] = $salt;
                $data['password'] = $password;
            }

            //判断是否有选择城市信息
            $region = $this->request->param('region', '', 'trim');

            if(!empty($region))
            {
                $path = $this->RegionModel->where(['code' => $region])->value('parentpath');

                if(!empty($path))
                {
                    $list = explode(',', $path);
                    
                    if(isset($list[0]))
                    {
                        $data['province'] = $list[0];
                    }

                    if(isset($list[1]))
                    {
                        $data['city'] = $list[1];
                    }

                    if(isset($list[2]))
                    {
                        $data['district'] = $list[2];
                    }
                }
            }

            //判断是否有图片上传
            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0 && $_FILES['avatar']['size'] > 0)
            {
                $success = upload('avatar');

                if(!$success['result'])
                {
                    $this->error($success['msg']);
                    exit;
                }

                $data['avatar'] = $success['data'];
            }

            $result = $this->BusinessModel->validate('common/Business.edit')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 册除旧的图片
            if(isset($data['avatar']))
            {
                $avatar = empty($business['avatar']) ? '' : "./".trim($business['avatar'], '/');
                @is_file($avatar) && @unlink($avatar);
            }

            //查询最新一次记录
            $business = $this->BusinessModel->find($id);

            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'nickname' => $business['nickname'],
                'avatar' => $business['avatar_text'],
                'gender' => $business['gender'],
                'province' => $business['province_text'],
                'city' => $business['city_text'],
                'district' => $business['district_text'],
                'region' => $business['region_text'],
                'createtime' => $business['createtime'],
                'address' => $business['address'],
            ];

            $this->success('更新资料成功', $data);
        }
    }
}